package com.mzm.tests;

import java.io.IOException;
import java.io.InputStream;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.StatementCallback;

public class DbTestUtils {

	@Resource
	private JdbcTemplate jdbcTemplate;

	public JdbcTemplate getJdbcTemplate() {
		return jdbcTemplate;
	}

	@Required
	@Autowired
	public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}

	public List<UpdateStatus> deleteAll() {
		InputStream is = getResourceAsStream("delete_all.sql");
		String sql = stream2String(is);
		return executeSqlBatch(sql);
	}

	@SuppressWarnings("unchecked")
	private List<UpdateStatus> executeSqlBatch(String batch) {
		String[] sqls = StringUtils.split(batch, ";");
		List<UpdateStatus> statuses = new ArrayList<UpdateStatus>();
		for (final String sql : sqls) {
			final String sq = sql.trim();
			if (sq.isEmpty()) {
				continue;
			}
			// System.err.println("|"+sq+"|");

			int rowsAffected = (Integer) jdbcTemplate
					.execute(new StatementCallback() {

						@Override
						public Object doInStatement(Statement stmt)
								throws SQLException, DataAccessException {
							return stmt.executeUpdate(sq);
						}
					});
			statuses.add(new UpdateStatus(sq, rowsAffected));
		}
		return statuses;
	}

	private InputStream getResourceAsStream(String s) {
		InputStream is = getClass().getResourceAsStream(s);
		return is;
	}

	private String stream2String(InputStream is) {
		try {
			return IOUtils.toString(is);
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		} finally {
			try {
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
